package com.loopy.fruns.service.impl;

import com.loopy.fruns.dao.FurnDAO;
import com.loopy.fruns.dao.OrderDAO;
import com.loopy.fruns.dao.OrderItemDAO;
import com.loopy.fruns.dao.impl.FurnDAOImpl;
import com.loopy.fruns.dao.impl.OrderDAOImpl;
import com.loopy.fruns.dao.impl.OrderItemDAOImpl;
import com.loopy.fruns.entity.*;
import com.loopy.fruns.service.OrderService;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public class OrderServiceImpl implements OrderService {
    private OrderDAO orderDAO = new OrderDAOImpl();
    private OrderItemDAO orderItemDAO = new OrderItemDAOImpl();
    private FurnDAO furnDAO=new FurnDAOImpl();
    @Override
    public String saveOrder(Cart cart, int memberId) {
        String orderId=System.currentTimeMillis()+""+memberId;
        Order order = new Order(orderId, new Date(), cart.getTotalPrice(), memberId, 0);
        orderDAO.saveOrder(order);
        Map<Integer, CartItem> items = cart.getItems();
        for (CartItem cartItem : items.values()) {
            OrderItem orderItem = new OrderItem(null, cartItem.getName(), cartItem.getPrice(), cartItem.getCount(), cartItem.getTotalPrice(), order.getId());
            orderItemDAO.saveOrderItem(orderItem);
            Furn furn = furnDAO.queryFurnById(cartItem.getId());
            furn.setSales(furn.getSales()+cartItem.getCount());
            furn.setStock(furn.getStock()-cartItem.getCount());
            furnDAO.updateFurn(furn);
        }
        cart.clear();
        return orderId;
    }

    @Override
    public Order queryOrderById(String orderId) {
        Order order = orderDAO.queryOrderById(orderId);
        return order;
    }

    @Override
    public List<OrderItem> getOrderItemListByOrderId(String orderId) {
        List<OrderItem> orderItemListByOrderId = orderItemDAO.getOrderItemListByOrderId(orderId);
        return orderItemListByOrderId;
    }
}
